import { define, CydonElement, watch } from 'cydon'
import { error, upload } from '../utils'
import { API } from '../api'
import { preprocess, submitOnEnter } from '../utils/helper'
import { CPagination } from './CPagination'
import { DataFilter, getFilters } from './DataFilter'
import { SideBar } from './SideBar'
import { PostThumb } from './PostThumb'
import { dragText } from '../utils/directives'
import './CPagination'
import './SideBar'

const search = (c: PostView, f: DataFilter, p: CPagination) =>
	API.search(preprocess(c.expr),
		getFilters(f),
		f.getSortPattern(c.keys),
		(p.pageNum - 1) * p.perPage, p.perPage).then(([count, ...pids]) => {
			c.data.results = pids
			c.page.data.total = count
		}, error)

@define('post-view')
export class PostView extends CydonElement {
	//#region 属性
	keys = ['id', 'hash', "length(tags)-length(replace(tags,' ',''))", 'created_at', 'updated_at']

	/** 分页器 */
	page!: CPagination
	/** 筛选器 */
	filter!: DataFilter

	/** 搜索词 */
	expr = ''
	/** 搜索结果 */
	results: number[] = []
	/** 上传地址 */
	urls = ''
	/** 显示原图 */
	original = 0

	/** 侧边栏 */
	sidebar!: SideBar

	/** 帖子列表 */
	posts!: HTMLElement

	/** PID */
	get pid() { return this.sidebar.pid }
	//#endregion

	connectedCallback() {
		this.$directives = [dragText, ...this.$directives]
		super.connectedCallback()
		if (location.pathname.startsWith('/p')) {
			import('./PostThumb').then(() => this.search())
		}
		// eslint-disable @typescript-eslint/no-this-alias
		const that = this
		const filter = this.filter
		filter.keys = that.keys
		filter.columns = ['ID', '哈希', '标签数', '创建时间', '修改时间']
		// 监听筛选器变化
		let f: DataFilter
		watch(filter, function (this: DataFilter) {
			if (f)
				search(that, f, that.page)
			else
				f = this
		})
		watch(filter, function (this: DataFilter) {
			if (this.sortKeys && this.localFilters)
				that.updateValue('filter')
		})
		this.page.perPages = [5, 10, 20, 24, 50]
		// 监听分页器的页码变化
		watch(this.page, function (this: CPagination) {
			search(that, f, this)
		})
		this.addEventListener('file', (e: CustomEvent) => {
			upload(e.detail)
		})
		addEventListener('hashchange', () => this.updateValue('pid'))
	}

	/** 搜索 */
	search() {
		location.hash = ''
		search(this, this.filter, this.page).then(() =>
			this.sidebar.getTags(this.expr)).then(() => {
				this.page.data.pageNum = 1
			})
	}

	/** 选中帖子 */
	select(i: number) {
		const thumb = <PostThumb>this.posts.children[i]
		if (!thumb)
			return
		// TODO: 重构
		if (this.sidebar.classList.contains('edit'))
			thumb.classList.toggle('selected')
		else
			this.sidebar.view(thumb.post)
	}

	/** 上传 */
	upload(e: Event) {
		e.preventDefault()
		upload(this.urls.split('\n'))
	}

	//#region 事件

	/** 回车提交 */
	keyup = submitOnEnter

	//#endregion
}

declare global {
	interface HTMLElementTagNameMap {
		'post-view': PostView
	}
}
